import gc
import random
from datetime import datetime
import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.metrics import mean_absolute_error as mae
from sklearn.preprocessing import LabelEncoder


def xgb1_train():
    np.random.seed(70)
    random.seed(70)
    print("\nXGB1 读数据..")
    prop = pd.read_csv(r'.\input\ccf_first_round_shop_info.csv')
    # prop = pd.read_csv(r'.\input\feature.csv')
    train = pd.read_csv(r'.\input\ccf_first_round_user_shop_behavior.csv')
    test =  pd.read_csv(r'.\input\AB-evaluation_public.csv')
    print('XGB1模型数据预处理')
    prop = prop.drop(['category_id','longitude','latitude','price','mall_id'],axis=1)

    df_train = train.merge(prop, how='left', on='shop_id')
    print(test.shape)
    x_train = df_train.drop(['user_id','time_stamp', 'wifi_infos'],axis=1)
    y_train = pd.DataFrame()
    y_train['shop_id'] = x_train['shop_id'].values
    lal = LabelEncoder()
    lal.fit(list(y_train['shop_id']))
    y_train['shop_num'] = lal.transform(list(y_train['shop_id'].values))
    train_y = y_train['shop_num'].values
    x_test = test.drop(['row_id','user_id','mall_id','time_stamp','wifi_infos'],axis=1)

    shop = list(set(y_train['shop_id']))
    print('店铺个数=%d'%(len(shop)))
    print('配置XGBoost参数')
    x_train = x_train.drop(['shop_id'],axis=1)
    x_train = x_train.values.astype(np.float64, copy=False)
    xgb_params = {
        'eta': 0.05,  # 学习速率，减少可提高鲁棒性 0.01-0.2之间
        'max_depth': 3,
        # 'min_child_weight': 1,  # 对线性回归模型，表示叶子节点最小分配的个数
        # 'subsample': 0.8,  # 随机采样比率
        'objective': 'multi:softmax',
        'num_class': len(shop),
        'silent': 1
    }

    print('构建XGBoost矩阵')
    print(x_train.shape,train_y.shape)
    dtrain = xgb.DMatrix(x_train, label=train_y)
    dtest = xgb.DMatrix(x_test)

    num_rounds = 250
    print("XGB1 num_rounds =" + str(num_rounds))

    print('训练XGBoost模型 ...')
    model = xgb.train(xgb_params, dtrain, num_boost_round=num_rounds)

    print('XGBoost预测 ..')
    xgb_pred1 = model.predict(dtest)

    # 写结果到磁盘
    print('写结果到磁盘中..')
    y_pred=pd.DataFrame()
    y_pred['predict']=xgb_pred1
    y_pred.to_csv(r'.\input\xgb1_predict.csv', index=False)
    print('结束')

    del x_train
    del x_test
    del y_train
    del prop
    del dtest
    del dtrain
    del model
    gc.collect()
    return xgb_pred1

if __name__ =="__main__":
    xgb1_train()
    